<template>
    <div>
        <h1>测试上传</h1>
        <el-upload
            class="upload-demo"
            name='pic'
            :with-credentials="true"
            action="http://localhost:8080/oss/upload/img"
            :before-upload="beforeUpload"
           
            :headers="dataObj"
           
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
         <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="fileList[0].url" alt="">
        </el-dialog>        
    </div>
</template>

<script>
    
    import COS from 'cos-js-sdk-v5'
    import {testUpload,testUpload2 }from '@/api/brand'
    import { getToken } from '@/utils/auth' // 验权
   export default {

    data() {
      return {
          dataObj:{
            TmpSecretId:'',
            TmpSecretKey:'',
            XCosSecurityToken:'',
            ExpiredTime:'',
           // loginToken:'',//
           // Authorization:"",
            //'Content-type':"multipart/form-data",
            //'Access-Control-Allow-Origin': '*'
          },
          dialogVisible: false,
          cos:{},
      };
    },
    computed: {
      
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
      fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function () {
          return this.value !== null && this.value !== ''&& this.value!==undefined;
        },
        set: function (newValue) {
        }
      }
    },
    mounted(){
      //  this.uploadInit();
    //    testUpload().then(res=>{
    //        console.og(res);
    //    })
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        let _self = this;
        let loginToken = getToken();
        console.log(loginToken)
        // testUpload().then((response)=>{
        //     //console.log(response.data);
        //     //console.log(JSON.parse(response.data));
        //     let data = response.data;
        //     _self.dataObj.TmpSecretId = data.credentials.tmpSecretId;
        //     _self.dataObj.TmpSecretKey = data.credentials.tmpSecretKey;
        //     _self.dataObj.XCosSecurityToken = data.credentials.sessionToken;
        // // _self.dataObj.key = response.data.dir + '/${filename}';
        // // _self.dataObj.dir = response.data.dir;
        //     _self.dataObj.ExpiredTime = data.expiredTime;
        //     _self.dataObj.loginToken =loginToken;
        // })
        
        _self.dataObj.loginToken =loginToken;
        _self.dataObj.Authorization =loginToken;
        // var Bucket = 'ys-mall-product-1300674810';
        // var Region = 'ap-chengdu';

        // // 初始化实例
        // _self.cos = new COS({
        //     getAuthorization: function (options, callback) {
        //         testUpload().then((response)=>{
        //             console.log(response);
        //             _self.dataObj.TmpSecretId = response.data.TmpSecretId;
        //             _self.dataObj.TmpSecretKey = response.data.TmpSecretKey;
        //             _self.dataObj.XCosSecurityToken = response.data.XCosSecurityToken;
        //         // _self.dataObj.key = response.data.dir + '/${filename}';
        //         // _self.dataObj.dir = response.data.dir;
        //             _self.dataObj.ExpiredTime = response.data.ExpiredTime;
        //         })
        //     }
        // });
        // return new Promise((resolve, reject) => {
        //   testUpload().then(response => {
        //     _self.dataObj.TmpSecretId = response.data.TmpSecretId;
        //     _self.dataObj.TmpSecretKey = response.data.TmpSecretKey;
        //     _self.dataObj.XCosSecurityToken = response.data.XCosSecurityToken;
        //    // _self.dataObj.key = response.data.dir + '/${filename}';
        //    // _self.dataObj.dir = response.data.dir;
        //     _self.dataObj.ExpiredTime = response.data.ExpiredTime;
        //     // _self.dataObj.callback = response.data.callback;
        //     resolve(true)
        //   }).catch(err => {
        //     console.log(err)
        //     reject(false)
        //   })
        // })
      },
      handleUploadSuccess(res, file) {
        this.showFileList = true;
        this.fileList.pop();
        this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name});
        console.log(this.fileList[0].url);
        //this.emitInput(this.fileList[0].url);
      },
      onProgress(event, file, fileList){
        //  testUpload2();



        // let _self = this;
        // console.log(file);
        // var file = file;
        // if (!file) return;
        // cos.putObject({
        //     Bucket: 'examplebucket-1250000000',
        //     Region: 'ap-beijing',
        //     Key: '目标路径/' + file.name,
        //     Body: file,
        // }, function (err, data) {
        //     console.log(err || data);
        // });
      },
      uploadInit(){
          //var fs = require('fs');
        var Bucket = 'ys-mall-product-1300674810';
        var Region = 'ap-chengdu';

        // 初始化实例
        var cos = new COS({
            getAuthorization: function (options, callback) {
                testUpload().then((res)=>{
                    console.log(res);
                })
            }
        });
        // cos.putObject({
        //     Bucket: Bucket, /* 必须 */
        //     Region: Region,    /* 必须 */
        //     Key: 'xdmz.png',              /* 必须 */
        //     StorageClass: 'STANDARD',
        //     Body: fs.createReadStream('./xdmz.png'), // 上传文件对象
        //     onProgress: function(progressData) {
        //         console.log(JSON.stringify(progressData));
        //     }
        // }, function(err, data) {
        //     console.log(err || data);
        // });
      },
      handleUpload(){
          testUpload2();
        //   console.log(e);
        //    var Bucket = 'ys-mall-product-1300674810';
        // var Region = 'ap-chengdu';

        // // 初始化实例
        // var cos = new COS({
        //     getAuthorization: function (options, callback) {
        //         testUpload().then((res)=>{
        //             console.log(res);
        //         })
        //     }
        // });
        //    var file = this.files[0];
        //     if (!file) return;
        //     cos.putObject({
        //         Bucket: 'examplebucket-1250000000',
        //         Region: 'ap-beijing',
        //         Key: '目标路径/' + file.name,
        //         Body: file,
        //     }, function (err, data) {
        //         console.log(err || data);
        //     });
                        // document.getElementById('file-selector').onchange = function () {
                        //     var file = this.files[0];
                        //     if (!file) return;
                        //     cos.putObject({
                        //         Bucket: 'examplebucket-1250000000',
                        //         Region: 'ap-beijing',
                        //         Key: '目标路径/' + file.name,
                        //         Body: file,
                        //     }, function (err, data) {
                        //         console.log(err || data);
                        //     });
                        // };
      }
    }
  }
</script>